//
//  KChart.m
//  iPad
//
//  Created by 英傑 翁 on 12/7/1.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//

#import "KChart.h"
#import "MGTreeViewController.h"
#import "MGChartViewController.h"
#import "MGSplitViewController.h"
#import "GBall.h"
#import "SourceListItem.h"
#import "PXTableObject.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBTableColumnHeader_key.h"


@implementation KChart

-(void)set_cchart_frame:(CGRect)frame{
    //NSLog(@"set_cchart_frame");

    [hostView setFrame:CGRectMake(0, 0, frame.size.width, frame.size.height-44) ];

}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //注意要透過上一層繪完框架之後 在重新繪一次
        
        hostView= [[CPTGraphHostingView alloc] initWithFrame: CGRectMake(0, 0, frame.size.width, frame.size.height) ];
        
        
        [self  addSubview: hostView];            
        
        // Create graph
        graph = [[(CPTXYGraph *)[CPTXYGraph alloc] initWithFrame:frame] autorelease];
        graph.fill			 = [CPTFill fillWithColor:[CPTColor darkGrayColor]];
        graph.cornerRadius	 = 20.0;
        hostView.hostedGraph = graph;
        
        // Plot area
        graph.plotAreaFrame.fill		  = [CPTFill fillWithColor:[CPTColor lightGrayColor]];
        graph.plotAreaFrame.paddingTop	  = 2.0;
        graph.plotAreaFrame.paddingBottom = 5.0;
        graph.plotAreaFrame.paddingLeft	  = 5.0;
        graph.plotAreaFrame.paddingRight  = 2.0;
        graph.plotAreaFrame.cornerRadius  = 1.0;
        
        graph.plotAreaFrame.axisSet.borderLineStyle = [CPTLineStyle lineStyle];
        
        graph.plotAreaFrame.plotArea.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
        
        // Setup plot space
        plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
        plotSpace.xRange	 = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(1000)];
        plotSpace.yRange	 = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(50) length:CPTDecimalFromDouble(150)];
        
        
        //[graph addPlotSpace:plotSpace];  很重要如果增加此行 就會出現兩個plotSpace     
        
        // Line styles
        CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
        axisLineStyle.lineWidth = 3.0;
        axisLineStyle.lineCap	= kCGLineCapRound;
        
        CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
        majorGridLineStyle.lineWidth = 0.75;
        majorGridLineStyle.lineColor = [CPTColor redColor];
        
        CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
        minorGridLineStyle.lineWidth = 0.25;
        minorGridLineStyle.lineColor = [CPTColor blueColor];
        
        // Text styles
        CPTMutableTextStyle *axisTitleTextStyle = [CPTMutableTextStyle textStyle];
        axisTitleTextStyle.fontName = @"Helvetica Bold";
        axisTitleTextStyle.fontSize = 14.0;
        
        // Axes
        // Label x axis with a fixed interval policy
        CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
        CPTXYAxis *x		  = axisSet.xAxis;
        x.separateLayers			  = NO;
        x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(0.5);
        x.majorIntervalLength		  = CPTDecimalFromString(@"0.5");
        x.minorTicksPerInterval		  = 4;
        x.tickDirection				  = CPTSignNone;
        x.axisLineStyle				  = axisLineStyle;
        x.majorTickLength			  = 12.0;
        x.majorTickLineStyle		  = axisLineStyle;
        x.majorGridLineStyle		  = majorGridLineStyle;
        x.minorTickLength			  = 8.0;
        x.minorGridLineStyle		  = minorGridLineStyle;
        x.title						  = @"X Axis";
        x.titleTextStyle			  = axisTitleTextStyle;
        x.titleOffset				  = 25.0;
        x.alternatingBandFills		  = [NSArray arrayWithObjects:[[CPTColor redColor] colorWithAlphaComponent:0.1], [[CPTColor greenColor] colorWithAlphaComponent:0.1], nil];
        x.labelingPolicy			  = CPTAxisLabelingPolicyAutomatic;
        
        // Label y with an automatic label policy.
        axisLineStyle.lineColor = [CPTColor greenColor];
        
        CPTXYAxis *y = axisSet.yAxis;
        y.separateLayers		= YES;
        y.minorTicksPerInterval = 9;
        y.tickDirection			= CPTSignNone;
        y.axisLineStyle			= axisLineStyle;
        y.majorTickLength		= 12.0;
        y.majorTickLineStyle	= axisLineStyle;
        y.majorGridLineStyle	= majorGridLineStyle;
        y.minorTickLength		= 8.0;
        y.minorGridLineStyle	= minorGridLineStyle;
        y.title					= @"Y Axis";
        y.titleTextStyle		= axisTitleTextStyle;
        y.titleOffset			= 30.0;
        y.alternatingBandFills	= [NSArray arrayWithObjects:[[CPTColor blueColor] colorWithAlphaComponent:0.1], [NSNull null], nil];
        y.labelingPolicy		= CPTAxisLabelingPolicyAutomatic;
        
        CPTFill *bandFill = [CPTFill fillWithColor:[[CPTColor darkGrayColor] colorWithAlphaComponent:0.5]];
        [y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(7.0) length:CPTDecimalFromDouble(1.5)] fill:bandFill]];
        [y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(1.5) length:CPTDecimalFromDouble(3.0)] fill:bandFill]];
        
        //走勢圖
        dataSourceLinePlot1=  [[CPTScatterPlot alloc] init]  ;
        dataSourceLinePlot1.identifier = @"Plot1";
        
        CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
        lineStyle.lineWidth = 1.0f;
        lineStyle.lineColor =[CPTColor blackColor];        
        
        dataSourceLinePlot1.dataLineStyle =lineStyle;
        
        dataSourceLinePlot1.dataSource = self;	
        
        [graph addPlot:dataSourceLinePlot1 toPlotSpace:plotSpace];	
        
        
        
        [dataSourceLinePlot1 release];       
    }
    return self;
}




-(void)viewDidLoad
{
      
    
    // Create graph from theme
    graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    hostView.hostedGraph = graph;
    
    
    
    
    CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
    [graph applyTheme:theme];
  
   
    
    graph.paddingLeft   = 10.0;
    graph.paddingTop    = 10.0;
    graph.paddingRight  = 10.0;
    graph.paddingBottom = 10.0;
    
    // Setup plot space
    plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;
    plotSpace.xRange                = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.0) length:CPTDecimalFromFloat(2.0)];
    plotSpace.yRange                = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.0) length:CPTDecimalFromFloat(3.0)];
    
    // Axes
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x          = axisSet.xAxis;
    x.majorIntervalLength         = CPTDecimalFromString(@"0.5");
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"2");
    x.minorTicksPerInterval       = 2;
    NSArray *exclusionRanges = [NSArray arrayWithObjects:
                                [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.99) length:CPTDecimalFromFloat(0.02)],
                                [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.99) length:CPTDecimalFromFloat(0.02)],
                                [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(2.99) length:CPTDecimalFromFloat(0.02)],
                                nil];
    x.labelExclusionRanges = exclusionRanges;
    
    CPTXYAxis *y = axisSet.yAxis;
    y.majorIntervalLength         = CPTDecimalFromString(@"0.5");
    y.minorTicksPerInterval       = 5;
    y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"2");
    exclusionRanges               = [NSArray arrayWithObjects:
                                     [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.99) length:CPTDecimalFromFloat(0.02)],
                                     [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.99) length:CPTDecimalFromFloat(0.02)],
                                     [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(3.99) length:CPTDecimalFromFloat(0.02)],
                                     nil];
    y.labelExclusionRanges = exclusionRanges;
    
    // Create a green plot area
    CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
    dataSourceLinePlot.identifier = @"Green Plot";
    
    CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
    lineStyle.lineWidth              = 3.f;
    lineStyle.lineColor              = [CPTColor greenColor];
    lineStyle.dashPattern            = [NSArray arrayWithObjects:[NSNumber numberWithFloat:5.0f], [NSNumber numberWithFloat:5.0f], nil];
    dataSourceLinePlot.dataLineStyle = lineStyle;
    
    dataSourceLinePlot.dataSource = self;
    
    // Put an area gradient under the plot above
    CPTColor *areaColor       = [CPTColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:areaColor endingColor:[CPTColor clearColor]];
    areaGradient.angle = -90.0f;
    CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    dataSourceLinePlot.areaFill      = areaGradientFill;
    dataSourceLinePlot.areaBaseValue = CPTDecimalFromString(@"1.75");
    
    // Animate in the new plot, as an example
    dataSourceLinePlot.opacity        = 0.0f;
    dataSourceLinePlot.cachePrecision = CPTPlotCachePrecisionDecimal;
    [graph addPlot:dataSourceLinePlot];
    
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimation.duration            = 1.0f;
    fadeInAnimation.removedOnCompletion = NO;
    fadeInAnimation.fillMode            = kCAFillModeForwards;
    fadeInAnimation.toValue             = [NSNumber numberWithFloat:1.0];
    [dataSourceLinePlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
    
    // Create a blue plot area
    CPTScatterPlot *boundLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
    boundLinePlot.identifier = @"Blue Plot";
    
    lineStyle            = [[boundLinePlot.dataLineStyle mutableCopy] autorelease];
    lineStyle.miterLimit = 1.0f;
    lineStyle.lineWidth  = 3.0f;
    lineStyle.lineColor  = [CPTColor blueColor];
    
    boundLinePlot.dataSource     = self;
    boundLinePlot.cachePrecision = CPTPlotCachePrecisionDouble;
    boundLinePlot.interpolation  = CPTScatterPlotInterpolationHistogram;
    [graph addPlot:boundLinePlot];
    
    // Do a blue gradient
    CPTColor *areaColor1       = [CPTColor colorWithComponentRed:0.3 green:0.3 blue:1.0 alpha:0.8];
    CPTGradient *areaGradient1 = [CPTGradient gradientWithBeginningColor:areaColor1 endingColor:[CPTColor clearColor]];
    areaGradient1.angle         = -90.0f;
    areaGradientFill            = [CPTFill fillWithGradient:areaGradient1];
    boundLinePlot.areaFill      = areaGradientFill;
    boundLinePlot.areaBaseValue = [[NSDecimalNumber zero] decimalValue];
    
    // Add plot symbols
    CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
    symbolLineStyle.lineColor = [CPTColor blackColor];
    CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    plotSymbol.fill          = [CPTFill fillWithColor:[CPTColor blueColor]];
    plotSymbol.lineStyle     = symbolLineStyle;
    plotSymbol.size          = CGSizeMake(10.0, 10.0);
    boundLinePlot.plotSymbol = plotSymbol;
    
    // Add some initial data
    NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
    NSUInteger i;
    for ( i = 0; i < 60; i++ ) {
        id x = [NSNumber numberWithFloat:1 + i * 0.05];
        id y = [NSNumber numberWithFloat:1.2 * rand() / (float)RAND_MAX + 1.2];
        [contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
    }
    dataForPlot = contentArray;    
    [graph reloadData];
}
    
    /*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
-(void)drawgraph:(NSMutableArray *)serialdata{
  /*
    for (NSMutableDictionary *sd in  serialdata) {
        
        NSLog(@"draw=%@",[sd objectForKey:HIS_basic_date] );
    }
    */
   
    if (history_data_serial) {
        
        [history_data_serial release];
       // NSLog(@"history_data_serial count=%i",[history_data_serial retainCount]);
    }
    
   
    
    history_data_serial=[serialdata retain];    
    
    
    //2.修正走圖設定
    //走勢圖區間的高低
    double high;
    double low;
    
    int index_satat;
    index_satat=0;
    high=[[[history_data_serial objectAtIndex:index_satat] objectForKey:HIS_basic_adjclose ] doubleValue ];
    low=[[[history_data_serial objectAtIndex:index_satat] objectForKey:HIS_basic_adjclose ] doubleValue ];
    
    for (int i=index_satat; i< [history_data_serial count]; i++) {
        if (high<[[[history_data_serial objectAtIndex:i] objectForKey:HIS_basic_adjclose ] doubleValue ]) {
            high=[[[history_data_serial objectAtIndex:i] objectForKey:HIS_basic_adjclose ] doubleValue ];
        }
        if (low>[[[history_data_serial objectAtIndex:i] objectForKey:HIS_basic_adjclose ] doubleValue ]) {
            low=[[[history_data_serial objectAtIndex:i] objectForKey:HIS_basic_adjclose ] doubleValue ];
        }
    }
    NSLog(@"high=%f low=%f",high,low);
    
    y_high_low=high-low;
    y_low=low;
    
    plotSpace.yRange	 = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(low) length:CPTDecimalFromDouble(high-low )];    
    
    plotSpace.xRange	 = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble([history_data_serial count]-1)];    
    
    plotSpace.delegate=self;        
    plotSpace.identifier=@"plotSpace_volume";      
    
    
    
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x		  = axisSet.xAxis;
    x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(low);    
    
    //如果要讓滑鼠點擊產生事件必須的
    graph.defaultPlotSpace.delegate = self;    
    
    //3.開始輸入繪圖資料
    [graph reloadData];  
    
    
    
}


#pragma mark -
#pragma mark Plot Data Source Methods

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
   
    
    return [history_data_serial count];
    
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    NSNumber *num = [NSDecimalNumber numberWithFloat:0];    
    
    
    if ( fieldEnum == CPTScatterPlotFieldY ) {
        NSDictionary *dic;
        dic=[history_data_serial objectAtIndex:index];
        double close=[[dic objectForKey:HIS_basic_adjclose ] doubleValue ];
        
        
        num = [NSDecimalNumber numberWithDouble:close];		
        
    }
    if(fieldEnum== CPTTradingRangePlotFieldX) 
        num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];    
    
    
	return num;	  
}

- (void)dealloc
{
    
        
    [history_data_serial release];
	
    [super dealloc];
}
 


@end
